"""
create_token  生成token
parse_payload  对token进行和发行校验并获取payload
"""
import jwt
import datetime
from jwt import exceptions
from django.conf import settings

salt = settings.SECRET_KEY


def create_token(payload, timeout=30):
    """
    生成token
    :param payload: 字典数据载体
    :param timeout: 设置token超时时间，默认30分钟
    :return: token
    """

    # 构造headers
    headers = {
        'typ': 'jwt',
        'alg': 'HS256',
    }
    # 构造payload
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)  # 超时时间
    # 生成token值
    token = jwt.encode(payload=payload, key=salt, algorithm="HS256", headers=headers)  # 新版不需要decode('utf-8')

    return token


def parse_payload(token):
    """
    对token进行和发行校验并获取payload
    :param token:
    :return:
    """
    result = {'status': False, 'data': None, 'error': None}
    try:
        verified_payload = jwt.decode(token, salt, True)
        result['status'] = True
        result['data'] = verified_payload

    except exceptions.ExpiredSignatureError:
        result['error'] = 'token已失效'
    except jwt.DecodeError:
        result['error'] = 'token认证失败'
    except jwt.InvalidTokenError:
        result['error'] = '非法的token'

    return result
